package com.alibaba.csp.sentinel.dashboard.rule;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.AuthorityRuleEntity;
import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.DegradeRuleEntity;
import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.FlowRuleEntity;
import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.ParamFlowRuleEntity;
import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.SystemRuleEntity;
import com.alibaba.csp.sentinel.dashboard.rule.convert.AuthorityRuleConvert;
import com.alibaba.csp.sentinel.dashboard.rule.convert.DegradeRuleConvert;
import com.alibaba.csp.sentinel.dashboard.rule.convert.FlowRuleConvert;
import com.alibaba.csp.sentinel.dashboard.rule.convert.ParamFlowRuleConvert;
import com.alibaba.csp.sentinel.dashboard.rule.convert.SystemRuleConvert;
import com.alibaba.csp.sentinel.datasource.Converter;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRule;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRule;
import com.alibaba.fastjson.JSON;

/**
* @Description: TODO
* @author blueice
* @date 2021年3月25日 上午11:39:57
*
*/
@Configuration
public class DynamicRuleConfig
{
    @Bean
    public FlowRuleConvert flowRuleEntityEncoder() {
        return new FlowRuleConvert();
    }

    @Bean
    public Converter<String, List<FlowRuleEntity>> flowRuleEntityDecoder() {
        return s -> JSON.parseArray(s, FlowRuleEntity.class);
    }

    @Bean
    public ParamFlowRuleConvert paramFlowRuleEntityEncoder() {
        return new ParamFlowRuleConvert();
    }

    @Bean
    public Converter<String, List<ParamFlowRuleEntity>> paramFlowRuleEntityDecoder() {
        return s -> JSON.parseArray(s, ParamFlowRule.class).stream().filter(Objects::nonNull).map(ParamFlowRuleEntity::new).collect(Collectors.toList());
    }


    @Bean
    public DegradeRuleConvert degradeRuleEntityEncoder() {
        return new DegradeRuleConvert();
    }

    @Bean
    public Converter<String, List<DegradeRuleEntity>> degradeRuleEntityDecoder() {
        return s -> JSON.parseArray(s, DegradeRuleEntity.class);
    }

    @Bean
    public AuthorityRuleConvert authorityRuleConvert() {
        return new AuthorityRuleConvert();
    }

    @Bean
    public Converter<String, List<AuthorityRuleEntity>> authorityRuleEntityDecoder() {
        return s -> JSON.parseArray(s, AuthorityRule.class).stream().filter(Objects::nonNull).map(AuthorityRuleEntity::new).collect(Collectors.toList());
    }

    @Bean
    public SystemRuleConvert systemRuleConvert() {
        return new SystemRuleConvert();
    }

    @Bean
    public Converter<String, List<SystemRuleEntity>> systemRuleEntityDecoder() {
        return s -> JSON.parseArray(s, SystemRuleEntity.class);
    }

}
